/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package izsla.beans;

import izsla.entities.TripUser;
import izsla.sb.AddUserException;
import izsla.sb.UserManagementLocal;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;


/**
 *
 * @author aki
 */
public class NewUser {
    // REQ1
    @EJB
    private UserManagementLocal um;

    private TripUser user;
    private String password2;
    private String error;
   
    public NewUser() {
        user = new TripUser();
        user.setIsAdmin(false);
    }

    public String getError() {
        return error;
    }

    public TripUser getUser() {
        return user;
    }

    public String getPassword2() {
        return password2;
    }

    public void setPassword2(String password2) {
        this.password2 = password2;
    }

    /**
     * Adds a user and logs in imediatelly upon succes ful login.
     * On failure the login page is displayed.
     */
    public String add() {
        System.out.print("\n\n" + password2 + "\t" + user.getPassword());

        if(password2 == null || !password2.equals(user.getPassword())) {
            error = "Passwords does not match!";
            return "register";
        }

        try {
	    um.addUser(user);

            FacesContext fc = FacesContext.getCurrentInstance();
            fc.getExternalContext().getSessionMap().put("user", user);

            return "search";
	}
	catch(AddUserException e) {
	    error = e.getMessage();
            return "register";
	}
    }

}
